import Request from './luch-request/index.js';
import {
	baseUrl,
	version
} from './config.js';
import store from '@/store/index.js';
const http = new Request({
	baseURL: baseUrl,
	timeout: 20000,
	header: {
		'content-type': 'application/json'
	}
})
// 请求拦截器
http.interceptors.request.use(config => {
	const token = uni.getStorageSync('token');
	const invitecode = uni.getStorageSync('invitecode') || '';
	config.header = {
		...config.header,
		invitecode: `${invitecode}`,
		token: `${token}`
	};
	// console.log(config.header, "我是header")

	return config
}, error => {
	return Promise.reject(error)
})

// 响应拦截器
http.interceptors.response.use(response => {
	// uni.hideLoading();
	const res = response.data;
	if (res.code == 1 || res.code == 2) {
		return res;
	} else if (res.code == 401) {
		console.log("token失效了")
		uni.navigateTo({
			url: '/pages/login/login'
		})
		return res;
	} else {
		let title = res.message || res.msg || '请求失败';
		uni.showToast({
			title,
			icon: 'none'
		})
		return Promise.reject(res);
	}
}, error => {
	if (error.errMsg == "request:fail abort statusCode:-1 timeout") {
		uni.showToast({
			title: '请求超时',
			icon: 'none'
		})
		return Promise.reject(error)
	}
	let code = error.statusCode || 500;
	let msg = error?.data?.msg;
	let data = error?.data
	if (code == 301 || code == 401) {
		// 退出登录
		uni.navigateTo({
			url: '/pages/login/login'
		})
		return Promise.reject(data)
	} else if (code == 500) {
		uni.showToast({
			title: msg || '服务器错误',
			icon: 'none'
		})
		return Promise.reject(error);
	} else {
		let title = error.data.msg || '请求失败';
		uni.showToast({
			title,
			icon: 'none'
		})
		return Promise.reject(error);
	}
})

export default http